package cn.mw.cmdb.link.service;

import cn.mw.cmdb.exception.NetWorkLinkException;
import cn.mw.cmdb.link.entity.MwLinkBandWidthDto;
import cn.mw.cmdb.link.entity.MwNetWorkLinkDto;
import cn.mw.cmdb.link.enums.LinkFetchPortEnum;
import cn.mw.cmdb.link.param.LinkParam;
import cn.mw.cmdb.link.service.impl.MwNetWorkLinkServiceImpl;
import cn.mw.cmdb.param.zabbixResult.DetailMonitorItemDto;
import cn.mw.cmdb.template.constant.MwTemplateConfigurationConstant;
import cn.mw.main.api.common.ZabbixDubboService;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.constants.ZabbixMethodConstants;
import cn.mw.microMonitorCommon.entity.UnitResult;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import cn.mw.microMonitorCommon.util.UnitUtil;
import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * @description 线路带宽管理
 */
@Component
@Slf4j
public class LinkBandWidthManager {

    private final String BPS = "bps";
    private final String BAND_WIDTH_ITEM = "INTERFACE_BANDWIDTH";
    private final String HOST_IDS = "hostids";
    private final String FILTER = "filter";
    private final String TYPE = "type";
    private final String PARAMS = "params";

    public void editorBandWidth(MwNetWorkLinkDto netWorkLinkDto, MwNetWorkLinkServiceImpl workLinkService, ZabbixDubboService zabbixDubboService) {
        //获取带宽监控项信息
        String takeValuePort = netWorkLinkDto.getTakeValuePort();
        LinkFetchPortEnum linkFetchPortEnum = LinkFetchPortEnum.getLinkFetchPortEnum(takeValuePort);
        String interfaceName = null;
        String hostId = null;
        Integer serverId = null;
        switch (linkFetchPortEnum) {
            case ROOT:
                interfaceName = netWorkLinkDto.getSourceDevicePort();
                hostId = netWorkLinkDto.getSourceDeviceHostId();
                serverId = netWorkLinkDto.getSourceDeviceServerId();
                break;
            case TARGET:
                interfaceName = netWorkLinkDto.getTargetDevicePort();
                hostId = netWorkLinkDto.getTargetDeviceHostId();
                serverId = netWorkLinkDto.getTargetDeviceServerId();
        }
        if (StringUtils.isEmpty(interfaceName) || StringUtils.isEmpty(hostId) || serverId == null) {
            return;
        }
        LinkParam linkParam = new LinkParam();
        linkParam.setHostId(hostId);
        linkParam.setServerId(serverId);
        linkParam.setInterfaceName(interfaceName);
        MwLinkBandWidthDto bandWidthDto = workLinkService.getLinkBandWidthInfo(linkParam);
        UnitResult unitResult = UnitUtil.getValueMap(String.valueOf(netWorkLinkDto.getUpBandWidth()), BPS, netWorkLinkDto.getBandWidthUnit());
        long newBandWidth = new BigDecimal(unitResult.getValue()).longValue();
        long oldBandWidthNumber = 0;
        //带宽全部转为bps比较
        if (StringUtils.isNotEmpty(bandWidthDto.getUpBandWidth()) && StringUtils.isNotEmpty(bandWidthDto.getBandWidthUnits())) {
            UnitResult oldBandWidth = UnitUtil.getValueMap(bandWidthDto.getUpBandWidth(), BPS, bandWidthDto.getBandWidthUnits());
            oldBandWidthNumber = new BigDecimal(oldBandWidth.getValue()).longValue();
            if (new BigDecimal(unitResult.getValue()).compareTo(new BigDecimal(oldBandWidth.getValue())) == 0) {
                return;
            }
        }
        if(newBandWidth == 0 || oldBandWidthNumber == 0){
            return;
        }
        Map zabbixParam = new HashMap();
        zabbixParam.put(MwTemplateConfigurationConstant.OUTPUT, MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(HOST_IDS, hostId);
        zabbixParam.put(MwTemplateConfigurationConstant.selectTags, MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectPreprocessing, MwTemplateConfigurationConstant.EXTEND);
        Map filterMap = new HashMap();
        filterMap.put(MwTemplateConfigurationConstant.NAME, "[" + interfaceName + "]" + BAND_WIDTH_ITEM);
        zabbixParam.put(FILTER, filterMap);
        //查询数据
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, serverId, ZabbixMethodConstants.ITEM_GET, zabbixParam);
        if (zabbixAPIResult == null || zabbixAPIResult.isFail()) {
            throw new NetWorkLinkException("查询带宽监控异常:" + String.valueOf(zabbixAPIResult.getData()));
        }
        //数据转为实体
        List<DetailMonitorItemDto> monitorItemDtos = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), DetailMonitorItemDto.class);
        if (CollectionUtils.isEmpty(monitorItemDtos)) {
            return;
        }
        DetailMonitorItemDto detailMonitorItemDto = monitorItemDtos.get(0);
        //删除该数据
        MWZabbixAPIResult deleteResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, serverId, ZabbixMethodConstants.ITEM_DELETE, Arrays.asList(detailMonitorItemDto.getItemid()));
        if (deleteResult == null || deleteResult.isFail()) {
            throw new NetWorkLinkException("删除带宽监控异常:" + String.valueOf(deleteResult.getData()));
        }
        //重新设置带宽倍数，并添加
        detailMonitorItemDto.setItemid(null);
        List<Map> preprocessing = detailMonitorItemDto.getPreprocessing();
        for (Map map : preprocessing) {
            if (map != null && map.containsKey(TYPE) && map.containsKey(PARAMS)) {
                Object o = map.get(TYPE);
                if(o != null && Integer.parseInt(String.valueOf(o)) == 1){
                    map.put(TYPE, 1);
                    double v = (double) newBandWidth / oldBandWidthNumber;
                    BigDecimal decimal = new BigDecimal(String.valueOf(v)).multiply(new BigDecimal(String.valueOf(map.get(PARAMS))));
                    String value = decimal.setScale(0,BigDecimal.ROUND_HALF_UP).toString();
                    map.put(PARAMS, value);
                }
            }
        }

        Map createItemParam = ListMapObjUtils.beanToMap(detailMonitorItemDto);
        delMapNullValue(createItemParam);
        MWZabbixAPIResult createItemResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, serverId, ZabbixMethodConstants.ITEM_CREATE, createItemParam);
        if (createItemResult == null || createItemResult.isFail()) {
            log.info("createItemParam>>>"+createItemParam);
            throw new NetWorkLinkException("创建新带宽监控异常:" + String.valueOf(createItemResult.getData()));
        }
    }


    public void delMapNullValue(Map zabbixParam){
        Iterator iterator = zabbixParam.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            if(entry.getValue() == null){
                iterator.remove();
            }else if(entry.getValue() instanceof List){
                List list = (List) entry.getValue();
                if(CollectionUtils.isEmpty(list)){
                    iterator.remove();
                }
            }
        }
    }
}
